package com.varteq.progress.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.varteq.progress.shared.ProgressChangeEvent;

public class ProgressChecker implements AsyncCallback<List<ProgressChangeEvent>> {
	private final String _progressName;
	private final int _progressCheckDelayMilliseconds;

	public ProgressChecker(String progressName) {
		this(progressName, 200);
	}

	public ProgressChecker(String progressName, int progressCheckDelayMilliseconds) {
		_progressName = progressName;
		_progressCheckDelayMilliseconds = progressCheckDelayMilliseconds;
	}

	public String getProgressName() {
		return _progressName;
	}

	@Override
	public void onSuccess(List<ProgressChangeEvent> result) {
		boolean keepChecking = true;

		if (result != null) {
			for (ProgressChangeEvent e : result) {
				if (e.isComplete()) {
					keepChecking = false;
				}
				onProgressChangeEvent(e);
			}
		} else {
			onProgressChangeEvent(null);
		}

		if (keepChecking) {
			scheduleProgressCheck();
		}
	}

	@Override
	public void onFailure(Throwable caught) {
		GWT.log("Progress check error", caught);
	}

	private final Timer _progressTimer = new Timer() {
		public void run() {
			ProgressService.Util.getInstance().getProgressEvents(_progressName, ProgressChecker.this);
		};
	};

	public void scheduleProgressCheck() {
		_progressTimer.schedule(_progressCheckDelayMilliseconds);
	}

	protected void onProgressChangeEvent(ProgressChangeEvent e) {
	}
}
